//CLIENT VARS

var extMaxAngle = 90;
var extWindowWidth = window.innerWidth-100;
var extWindowHeight = window.innerHeight;
var extOnVirtualAccelerometer = true;
var extOnVirtualMultiTouch = true;


//DRIVER VARS

var extSocket;


/*----------------------------DRIVER CODE------------------------------*/

function onOpen()
{
	OutputLog('Socket Status: '+extSocket.readyState+' (open)');
	var pseudoName = (new Date()).getTime()+"";
	extSocket.send('0'+pseudoName);
	//self.postMessage({"method":"onConnected","data":""});
	onDriverResponse({data:{"method":"onConnected","data":""}});
}

function onClose()
{
	OutputLog('Socket Status: '+extSocket.readyState+' (Closed)');
	//self.postMessage({"method":"onDisconnected","data":""});
	onDriverResponse({data:{"method":"onDisconnected","data":""}});
}		

function onMessageDriver(msg)
{
	var str = "";
	str = msg.data;
	var id  = str.substr(0, 1);
	var separator = str.indexOf("|");
	var arg1 = "";
	var arg2 = "";
	if(separator != -1)
	{
		arg1 = str.substr(1, separator-1);
		arg2 = str.substr(separator+1);
	}
	else
		arg1 = str.substr(1);				
	
	if(id == "0"){
		OutputLog('Server reply : '+arg1);	
	}
	if(id == "1"){
		OutputLog('Server echo msg : '+arg1);	
	}
	if(id == "2"){
		OutputLog(arg1 + ' said : ' + arg2);	 						
	}
	if(id == "3"){
		//OutputLog(arg1 + ' broadcasted : ' + arg2);
		onDatagram(arg2);
	}
	if(id == "4"){
		//OutputLog('Server streamed : '+arg1);	
		onDatagram(arg1);
	}		
	//self.postMessage({"method":"onMessage","data":arg1});
	onDriverResponse({data:{"method":"onMessageClient","data":arg1}});
}

function onDatagram(data)
{
	try
	{
		var datagram = eval("("+data+")");
		if(typeof datagram["DatagramType"] != 'undefined')
		{
			if(datagram["DatagramType"] == "INTERACTION")
			{
				//self.postMessage({"method":"onInteraction","data":datagram});
				onDriverResponse({data:{"method":"onInteraction","data":datagram}});
			}
			else if(datagram["DatagramType"] == "EVENT")
			{
				//self.postMessage({"method":"onEvent","data":datagram});
				onDriverResponse({data:{"method":"onEvent","data":datagram}});
			}
		}
	}
	catch(e)
	{
	}
}

function OutputLog(msg)
{
	//self.postMessage({"method":"onDebug","data":msg});
	onDriverResponse({data:{"method":"onDebug","data":msg}});
}

function disconnect(request)
{
	try
	{
		unsuscribeStream(request);
		extSocket.close();
		OutputLog('Disconnected');
	} 
	catch(exception)
	{
		OutputLog('Error'+exception);
	}
}

function suscribeGroup(request)
{
	extSocket.send('3subscribe');
}

function suscribeStream(request)
{
	extSocket.send('4subscribe');
}

function unsuscribeStream(request)
{
	extSocket.send('4unsubscribe');
}

function connect(request)
{
	try
	{
		extSocket = new WebSocket(request["url"]);
		OutputLog('Socket Status: '+extSocket.readyState);
		extSocket.onopen = onOpen;
		extSocket.onmessage = onMessageDriver;
		extSocket.onclose = onClose;		
	} 
	catch(exception)
	{
		OutputLog('Error'+exception);
	}
}

function getClientRequest(event) 
{
	var request = event.data;
	if(request["method"]=="echo")
	{
		OutputLog(request["data"]);
	}
	else if(request["method"]=="connect")
	{
		connect(request);
	}
	else if(request["method"]=="disconnect")
	{
		disconnect(request);
	}
	else if(request["method"]=="suscribeGroup")
	{
		suscribeGroup(request);
	}
	else if(request["method"]=="suscribeStream")
	{
		console.debug("Suscribed");
		suscribeStream(request);
	}
	else if(request["method"]=="unsuscribeStream")
	{
		unsuscribeStream(request);
	}
}

//self.addEventListener('message', getClientRequest, false);


/*----------------------------CLIENT CODE------------------------------*/

function sendEvent(name,data)
{
	if(name=="deviceorientation")
	{
		var event = document.createEvent("DeviceOrientationEvent");
		event.initDeviceOrientationEvent(name, true, true, data["alpha"], data["beta"], data["gamma"]);
		window.dispatchEvent(event);
	}
	else if(name=="touchstart"||name=="touchmove"||name=="touchend")
	{
		var event = document.createEvent("MouseEvents");
		event.initMouseEvent(name, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, document);
		event.touches = data["touches"];
		event.targetTouches = data["touches"];
		event.changedTouches = data["touches"];
		document.dispatchEvent(event);
	}
}

function fireEvent(data)
{
	if(data["Data"]["EventType"] == "INCLINATION")
	{
		fireEventInclination(data["Data"]["EventData"]);
	}
}

function fireEventInclination(data)
{
	if(data["Status"]=="START")
	{
	}
	else if(data["Status"]=="OVER")
	{
		if(extOnVirtualAccelerometer)
		{
			var eventData = {};
			eventData["alpha"] = 0;
			eventData["beta"] = -data["Data"]["Angles"]["Y"]*extMaxAngle;
			eventData["gamma"] = -data["Data"]["Angles"]["X"]*extMaxAngle;
			sendEvent("deviceorientation",eventData);
		}
	}
	else if(data["Status"]=="END")
	{
	}
}

function fireInteraction(data)
{
	if(extOnVirtualMultiTouch)
	{
		var eventName;
		if(data["Data"]["Status"]=="START")
		{
			eventName = "touchstart";
		}
		else if(data["Data"]["Status"]=="OVER")
		{
			eventName = "touchmove";
		}
		else if(data["Data"]["Status"]=="END")
		{
			eventName = "touchend";
		}
		var arrFingers = [];
		var fingers = data["Data"]["Fingers"];
		var listString = "document.createTouchList(";
		coma = "";
		for(var i in fingers)
		{
			var valX = (extWindowWidth/2)+(fingers[i]["Points"]["X"]*extWindowWidth);
			var valY = (extWindowHeight/2)-(fingers[i]["Points"]["Y"]*extWindowHeight);
			var valZ = fingers[i]["Points"]["Z"];
			var touchObj = document.createTouch(window, document, (new Date()).getTime(), valX, valY, valX, valY, valX, valY, valZ, valZ, valZ, valZ);
			arrFingers.push(touchObj);
			listString += coma + "arrFingers[" + i + "]";
			coma = ",";
		}
		listString += ")";
		//var listFingers = document.createTouchList(arrFingers);
		var listFingers = eval(listString);
		sendEvent(eventName,{"touches":listFingers});
	}
}

function onDebug(request)
{
	console.debug(request["data"]);
}

function onConnected(request)
{
	console.debug("Connected");
	//worker.postMessage({"method":"suscribeStream","user":""});
	getClientRequest({data:{"method":"suscribeStream","user":""}});
}

function onMessageClient(request)
{
	//console.debug(request["data"]);
}

function onInteraction(request)
{
	fireInteraction(request["data"]);
}

function onEvent(request)
{
	fireEvent(request["data"]);
}

function onDisconnected(request)
{
	console.debug("Disconnected");
}

function onDriverResponse(event)
{
	var request = event.data;
	if(request["method"]=="onDebug")
		onDebug(request);
	else if(request["method"]=="onConnected")
		onConnected(request);
	else if(request["method"]=="onMessageClient")
		onMessageClient(request);
	else if(request["method"]=="onInteraction")
		onInteraction(request);
	else if(request["method"]=="onEvent")
		onEvent(request);
	else if(request["method"]=="onDisconnected")
		onDisconnected(request);
}

function onDriverError(event)
{
}